
function ProcessUserListResult (data)
{  
    registerTemplate ("UserListNormalRow", UserListNormalRow);
    registerTemplate ("UserListSelectedRow", UserListSelectedRow);
    
    var d=new dgrid();
    d.key="eusertable";
    d.showall = true; 
    d.selected = Controller.SelectedUser; 

    d.headertransform = function ()
    {
        var htm = '';
        htm += '<div style="margin-bottom:10px">&nbsp;';
        htm += 'Create a new user: First <input id="ipf" class=flat value=""> Last <input id="ipl" class=flat value="">';
        htm += '<input onclick="CreateUser (getElement(\'ipf\').value,getElement(\'ipl\').value)" ';
        htm += ' type=button value="Create">';
        htm += '</div>';
        return htm; 
    }
    d.transform = function (row)
    {
        var ok=parseInt(this.selected)==parseInt(row['ID']);
        var object = { 'template' : ok ? 'UserListSelectedRow' : 'UserListNormalRow' , 
                        'gridid' : this.id,
                        'MaskTable' : MaskTable (row['Mask'], row['ID']),
                        'MaskEdit' : MaskEdit (row['Mask']) }  
        for (var x in row) object[x]=row[x]; 
        return  Factory.write (object);   
    }
	d.select = function (i)
	{ 
	    Controller.SelectedUser = i;
	    Controller.Reload (); 
	} 
	d.columns = new Array ('Salutation','Name','Title','EMail','UserID','Password','Phone','Mask');
	
	d.rows = window.users; 
	
	d.cellpadding= 2; 
    return d.draw(); 
}

var UserListNormalRow = ''; 
UserListNormalRow+='<tr>'; 
UserListNormalRow+="<td class='datarow' nowrap>(Salutation)&nbsp;</td>";
UserListNormalRow+="<td class='datarow' nowrap>";
UserListNormalRow += '<a href="./#view/userlist/id/(ID)">'; 
//UserListNormalRow+="<a href='javascript:void(0)' onclick='window.datagrids[(gridid)].select((ID))'>";
UserListNormalRow+="(LastName), (FirstName)";
UserListNormalRow+="</a>";
UserListNormalRow+="&nbsp;</td>";
UserListNormalRow+="<td class='datarow' nowrap>(Title)&nbsp;</td>";
UserListNormalRow+="<td class='datarow' nowrap>(EMail)&nbsp;</td>";
UserListNormalRow+="<td class='datarow' nowrap>(UserID)&nbsp;</td>";
UserListNormalRow+="<td class='datarow' nowrap>(Password)&nbsp;</td>";
UserListNormalRow+="<td class='datarow' nowrap>(Phone)&nbsp;</td>";
UserListNormalRow+="<td class='datarow' nowrap>(MaskTable)</td>"; 
UserListNormalRow+='</tr>';


var UserListSelectedRow = ''; 
UserListSelectedRow+='<tr>'; 
UserListSelectedRow+='<td nowrap><input id="iSalutation" value="(Salutation)" size="3"></td>';
UserListSelectedRow+='<td nowrap>';
UserListSelectedRow+='<input id="iLastName" value="(LastName)" size="10">, ';
UserListSelectedRow+='<input id="iFirstName" value="(FirstName)" size="10">';
UserListSelectedRow+='</td>';
UserListSelectedRow+='<td nowrap><input id="iTitle" value="(Title)" size="10"></td>';
UserListSelectedRow+='<td nowrap><input id="iEMail" value="(EMail)" size="20"></td>';
UserListSelectedRow+='<td nowrap><input id="iUserID" value="(UserID)" size="8"></td>';
UserListSelectedRow+='<td nowrap><input id="iPassword" value="(Password)" size="8" type="password"></td>';
UserListSelectedRow+='<td nowrap><input id="iPhone" value="(Phone)" size="10"></td>';
UserListSelectedRow+="<td nowrap>(MaskTable)</td>";
UserListSelectedRow+='</tr>';
UserListSelectedRow+='<tr>';  
UserListSelectedRow+='<td colspan="8" class="datarow" nowrap>';  
UserListSelectedRow+='<b>Permissions:</b> (MaskEdit)';   
UserListSelectedRow+='&nbsp;<input type=button value="Save" onclick="SaveUser()">';  
UserListSelectedRow+="<input type=button value='Cancel' onclick='window.datagrids[(gridid)].select(0)' >";  
UserListSelectedRow+='<input type=button value="Delete" onclick="DeleteUser((ID))">';  
UserListSelectedRow+='</td>';
UserListSelectedRow+='</tr>';


function MaskEdit (mask)
{  
    var num = parseInt (mask, 2);
    var htm = '';
	var bin=1;
	var x=0;
	for (var x=0;x<MaskEdit.names.length;x++) 
	{  
	    bin = Math.pow (2,x);
        htm = '<input type="checkbox" value="'+bin+'" id="iMask'+x+'" '+(bin & num?'checked':'')+'><small>'+MaskEdit.names[x] + '</small>' + htm;  
	}
	return htm;
}
MaskEdit.names=new Array ('Modify events','Create Events','Edit Rooms','Edit users','Browse events','Override conflicts');
MaskEdit.total=1; var bin=1;
for (var x in MaskEdit.names) { MaskEdit.total += bin; bin=bin*2; }

MaskEdit.PERM_MODIFY         = 1;
MaskEdit.PERM_CREATE_EVENT   = 2;
MaskEdit.PERM_EDIT_USER      = 8;
MaskEdit.PERM_EDIT_ROOM      = 4;
MaskEdit.PERM_BROWSE         = 16;
MaskEdit.PERM_OVERRIDE       = 32;
		
		
function MaskTable (mask, id)
{ 
	var td='';
    var num = parseInt (mask,2);// Bin2Number (mask);
    var htm = '';
	var bin=1; 
	for (var x=0;x<MaskEdit.names.length;x++)
	{  
	    bin = Math.pow (2,x);
	    
		td='';
        td += '<td title="User '+(bin & num?'CAN':'CANNOT')+' '+MaskEdit.names[x].toLowerCase() +'"';
        td += ' bgcolor="'+(bin & num?'lime':'red')+'"';
        td += ' onclick="ToggleUserPerm('+bin+','+id+')" ';
        td += ' valign="top"><img src="/webservices/images/clear.gif" border=1 width=10 height=10></td>';
		
        htm = td + htm; 
	}
    htm ='<table cellspacing=2 bgcolor=white cellpadding=0><tr>' + htm + '</tr></table>';
	return htm; 
}
 

function OnUserListRender ()
{ 
    AttachResizer ('dceusertable', (Controller.SidebarState==1?176:20), 120);
}


function UserLoginPreferences (dom)
{
	this.dom = dom;
	this.get = function (name)
	{
		try { return dom[name];
		} catch (ex) { }
		return false;
	} 
	this.userid   = this.get ('userid');
	this.password = this.get ('password'); 
	this.remember = this.get ('remember'); 
}


function Number2Bin (number)
{ 
	var value=''; 
	for (var i=0;i<MaskEdit.names.length;i++)
		value = (Math.pow(2,i) & number ? '1' : '0') + value;  
	return value;
}


function Bin2Number (string)
{
	var value=0;
	var bin=1;
	for (var x=string.length-1;x>=0;x--)
	{
		value += parseInt (string.substr(x,1))==1?bin:0;
		bin=bin*2;
	}
	return value;
}


function MVCUser (array)
{
	this.PERM_BROWSE         = false;
	this.PERM_EDIT_USER      = false;
	this.PERM_EDIT_ROOM      = false;
	this.PERM_CREATE_EVENT   = false;
	this.PERM_MODIFY         = false;
	this.dom = array;
	this.get = function (name)
	{
		try { return this.dom[name];
		} catch (ex) { }
		return false;
	}
	this.id         = this.get ('ID');
	this.name       = this.get ('FirstName');
	this.last       = this.get ('LastName');
	this.acl        = this.get ('ACL'); 
	this.mask       = this.get ('Mask'); 
	this.title      = this.get ('Title'); 
	this.mr         = this.get ('Salutation'); 
	this.email      = this.get ('EMail'); 
	this.userid     = this.get ('UserID'); 
	this.password   = this.get ('Password'); 
	this.phone      = this.get ('Phone'); 
	this.bitmask    = null;
	this.parsemask  = function ()
	{ 
		this.bitmask 			 = parseInt (this.mask, 2);   
		this.PERM_BROWSE         = this.bitmask & MaskEdit.PERM_BROWSE;
		this.PERM_EDIT_USER      = this.bitmask & MaskEdit.PERM_EDIT_USER;
		this.PERM_EDIT_ROOM      = this.bitmask & MaskEdit.PERM_EDIT_ROOM;
		this.PERM_CREATE_EVENT   = this.bitmask & MaskEdit.PERM_CREATE_EVENT;
		this.PERM_MODIFY         = this.bitmask & MaskEdit.PERM_MODIFY;
		this.PERM_OVERRIDE       = this.bitmask & MaskEdit.PERM_OVERRIDE; 
	}
	this.parsemask();
	this.Serialize = function ()
	{
        var htm='';
	    htm+='<user>\n'; 
        htm+='  <r>\n';
        for (var i in this.dom)
        {
            htm+='   <f n="'+i+'"><![CDATA[' + this.dom[i] + ']]></f>\n'; 
        }
        htm+='  </r>\n';   
	    htm+='</user>\n'; 
	    return htm;  
	}
	
	this.save = function ()
	{  
        var RequestParams = {  
            'aftersend' : ReLoadGlobalUserList ,
            'message' : 'Receiving save response...',
            'method' : 'POST',
            'postdata' : this.Serialize()
                  }; 
	    var ok=true;
	    if (this.id==window.loggedinuser.id && !this.PERM_EDIT_USER) ok=confirm ('Disabling your own PERM_EDIT_USER mask CANNOT be undone! Are you sure you want to continue?');
	    if (ok) window.request.create (RequestParams);   
	}
}


function GetUserName(id)
{
    var us=GetUserById(id);
    if (us)
    {
        return us['FirstName'] + ' ' + us['LastName'];
    }
    return 'User id '+id+' was not found';
}


function GetUserById(id)
{
    return GetObjectByAttribute (window.users, 'ID', id); 
}

function ToggleUserPerm (bit,id)
{
    var bot=-(bit-1);
    var us=GetUserById(id);
    if (us)
    {
		var num=parseInt (us['Mask'],2) 
		num = bite (num,bit) 
        us['Mask']=Number2Bin (num);   
        var user = new MVCUser (us);
        user.save ();   
    } 
} 
 
function SaveUser ()
{
    var us=GetUserById(Controller.SelectedUser);
    if (us)
    { 
        us['Salutation']=getElementValue('iSalutation'); 
        us['FirstName']=getElementValue('iFirstName'); 
        us['LastName']=getElementValue('iLastName'); 
        us['Title']=getElementValue('iTitle'); 
        us['EMail']=getElementValue('iEMail'); 
        us['UserID']=getElementValue('iUserID'); 
        us['Password']=getElementValue('iPassword'); 
        us['Phone']=getElementValue('iPhone'); 
		
        var mask=0;
        for (var x=0;x<MaskEdit.names.length;x++) mask += getElement ('iMask'+x).checked?parseInt(getElement ('iMask'+x).value):0;
        us['Mask']=Number2Bin(mask);  
         
        var user = new MVCUser (us);
        user.save ();   
    }  
//    for (var pt in window.users)
//    {
//        if (window.users[pt]['ID'] == Controller.SelectedUser)
//        {     
//            window.users[pt]['Salutation']=getElementValue('iSalutation'); 
//            window.users[pt]['FirstName']=getElementValue('iFirstName'); 
//            window.users[pt]['LastName']=getElementValue('iLastName'); 
//            window.users[pt]['Title']=getElementValue('iTitle'); 
//            window.users[pt]['EMail']=getElementValue('iEMail'); 
//            window.users[pt]['UserID']=getElementValue('iUserID'); 
//            window.users[pt]['Password']=getElementValue('iPassword'); 
//            window.users[pt]['Phone']=getElementValue('iPhone'); 
//			
//            var mask=0;
//            for (var x=0;x<MaskEdit.names.length;x++) mask += getElement ('iMask'+x).checked?parseInt(getElement ('iMask'+x).value):0;
//            window.users[pt]['Mask']=Number2Bin(mask);  
//             
//            var user = new MVCUser (window.users[pt]);
//            user.save ();   
//            break;
//        }
//    } 
} 

MVCUser.empty = function (firstname, lastname)
{ 
    return {
            'ID': 0,
            'Salutation' : '',
            'FirstName' : '',
            'LastName' : '',
            'Title' : '',
            'EMail' : '',
            'UserID' : '',
            'Password' : '',
            'Phone' : '',
            'ACL' : '0',
            'Mask' : '000000' 
            };
}